<template>
    <el-row>
        <el-col :span="8" style="padding-right: 10px;">
            <!-- 用户信息 -->
            <el-card class="box-card" style="margin-bottom: 20px;">
                <div class="user">
                    <img :src="showImg()"/>
                    <div class="userinfo">
                        <p class="name">权限：{{ user.permission }}</p>
                        <p class="access">账号：{{ user.id }}</p>
                    </div>
                </div>
                <div class="login-info" >
                    <p>上次登陆时间：<span>{{ getDate }}</span></p>
                    <p>上次登陆IP地址：<span>{{ user.lastLoginLocation }}</span></p>
                </div>
            </el-card>
            <!-- 模型可识别药材信息 -->
            <el-card class="box-card">
                <el-table :data="tableData" height="325" style="width: 100%">
                    <el-table-column prop="name" label="药材名称" width="80"></el-table-column>
                    <el-table-column prop="latin_name" label="拉丁学名" width="230"></el-table-column>
                    <el-table-column label="准确率" prop="accuracy_rate" sortable>
                        <template slot-scope="scope">
                            <el-progress :percentage="scope.row.accuracy_rate.toFixed(1)" :color="getStatus(`${scope.row.accuracy_rate}`)"></el-progress>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
            
        </el-col>
        <el-col :span="16" style="padding-left: 10px;">
            <!-- 模型信息显示 -->
            <div class="num">
                <el-card class="box-card" v-for="item in countData" :key="item.name" :body-style="{ display:'flex'}">
                    <i class="icon" :class="`el-icon-${item.icon}`" :style="{background:item.color}"></i>
                    <div class="detail" style="width: 191.7px;">
                        <p class="item_val" style="font-size: 15px;">{{ item.value }}</p>
                        <p class="item_name">{{ item.name }}</p>
                    </div>
                </el-card>
            </div>
            <el-card style="height:280px">
                <!-- 折线图 -->
                <div ref="echarts1" style="height: 280px;"></div>
            </el-card>
            <div class="graph">
                <el-card style="height: 260px;">
                    <div ref="echarts2" style="height: 260px;"></div>
                </el-card>
                <el-card style="height: 260px;">
                    <div ref="echarts3" style="height: 230px;"></div>
                </el-card>
            </div>
        </el-col>
    </el-row>
</template>
<script>
// import { getData } from '../api'
import * as echarts from 'echarts'
export default {
    data(){
        return {
            img:null,
            user:{
                id:"",
                permission:"",
                lastLoginTime:"",
                lastLoginLocation:"",
            },
            targetModel:{
                id: "",
                model:{
                    layearOne:{},
                    layearTwo:{},
                    layearThree:{}
                },
            },
            flowData:[],
            accuracy_rate:[],
            loss_rate:[],
            tableData: [],
            modelHerbTypeNum:{}
        }
    },
    methods:{
        dateFormat(time) {
            var date=new Date(time);
            var year=date.getFullYear();
            var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
            var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
            var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
            var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
            var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
            // 拼接
            return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
        },
        convertToImage(binaryString) {
          const byteCharacters = atob(binaryString); // 将base64编码的二进制字符串解码为原始字节流
          const byteArrays = [];
            for (let offset = 0; offset < byteCharacters.length; offset += 512) {
                const slice = byteCharacters.slice(offset, offset + 512);
                const byteNumbers = new Array(slice.length);
                for (let i = 0; i < slice.length; i++) {
                    byteNumbers[i] = slice.charCodeAt(i);
                  }
              const byteArray = new Uint8Array(byteNumbers);
              byteArrays.push(byteArray);
            }
          const blob = new Blob(byteArrays, { type: 'image/jpeg' }); // 根据实际情况设置MIME类型
          return URL.createObjectURL(blob); // 生成URL
        },
        showImg(){
          return this.convertToImage(this.img)
        },
        getUserInfo(){
          this.$axios.get('/getUserInfo').then(({data}) => {// 请求成功，返回
                if(data.code===200){
                    this.user.id=data.data.user.id
                    this.user.permission=data.data.user.permission
                    this.user.lastLoginTime=data.data.user.lastLoginTime
                    this.user.lastLoginLocation=data.data.user.lastLoginLocation
                    this.img=data.data.user.img
                    this.$message({
                        type: 'success',
                        message: data.data.message
                    });
                }else{
                    this.$message({
                        type: 'error',
                        message: data.data.message
                    });
                }
            })
            .catch((err) => {// 请求失败
                console.log(err);
            });
        },
        getModelHerbType(){
            this.$axios.get("/getModelHerbType",{params:{id:this.targetModel.id}}).then(({data}) => {
                this.modelHerbTypeNum=data.data.modelHerbTypeNum
                this.showPieChart()
            })
        },
        getStatus(val){
            let color=""
            if(val>=80){
                color="#409eff"
            }else if(val<80 && val>=60){
                color="#e6a23c"
            }else{
                color="#f56c6c"
            }
            return color
        },
        selectChanged(){
            this.$axios.get("/getModelData",{params:{id:this.targetModel.id}}).then(({data}) => {
                this.targetModel.model=data.data.targetModel
                this.tableData=data.data.tableData
                this.flowData=data.data.flowData
                this.accuracy_rate=data.data.trainDataMap.accuracy_rate
                this.loss_rate=data.data.trainDataMap.loss_rate
                this.showLineChart()
                this.showHistogram()
                console.log(this.targetModel.model)
                console.log(data)
            })

        },
        getModelList(){
            this.$axios.get("/getModelList").then(({data}) => {
                for (let i = 0; i < data.list.length; i++) {
                    if(data.list[i].status==1){
                        this.targetModel.id=data.list[i].id
                        this.selectChanged()
                        this.getModelHerbType()
                    }
                }
            })
        },
        showPieChart(){
            //饼状图
            const echarts3 = echarts.init(this.$refs.echarts3);
            const option = {
                title: {
                    text: '中草药比例'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                series: [
                    {
                    name: '药效种类',
                    type: 'pie',
                    radius: '50%',
                    center: ['50%', '60%'],
                    data: Object.entries(this.modelHerbTypeNum).map(([name, value]) => ({ name, value })),
                    emphasis: {
                        itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                    }
                ]
                };
            echarts3.setOption(option)
        },
        showLineChart(){
            const echarts1 = echarts.init(this.$refs.echarts1);
            // 配置图表选项
            const option = {
            title: {
                text: 'Accuracy and Loss Rates'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['Accuracy Rate', 'Loss Rate']
            },
            xAxis: {
                type: 'category',
                data: Array.from({length: this.accuracy_rate.length }, (val, i) => i+1)
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                name: 'Accuracy Rate',
                type: 'line',
                symbol: 'none',
                data: this.accuracy_rate
                },
                {
                name: 'Loss Rate',
                type: 'line',
                symbol: 'none',
                data: this.loss_rate
                }
            ]
            }
            echarts1.setOption(option) // 使用刚指定的配置项显示图表
        },
        showHistogram(){
            //柱状图
            const echarts2 = echarts.init(this.$refs.echarts2);
            const dates = Object.keys(this.flowData);
            const counts = dates.map(date => this.flowData[date].count);
            const goodCounts = dates.map(date => this.flowData[date].good);
            const ordinaryCounts = dates.map(date => this.flowData[date].ordinary);
            const badCounts = dates.map(date => this.flowData[date].bad);
            const option = {
                title: {
                text: '流量',
                },
                tooltip: {},
                legend: {
                data: ['总流量', '好评','一般','差评'],
                },
                xAxis: {
                data: dates,
                },
                yAxis: {},
                series: [
                {
                    name: '总流量',
                    type: 'bar',
                    data: counts,
                    color: '#87CEEB'
                },
                {
                    name: '好评',
                    type: 'bar',
                    data: goodCounts,
                    color: '#FF7F50'
                },
                {
                    name: '一般',
                    type: 'bar',
                    data: ordinaryCounts,
                    color: '#008080'
                },
                {
                    name: '差评',
                    type: 'bar',
                    data: badCounts,
                    color: '#A9A9A9'
                },
                ],
            };
            echarts2.setOption(option)
        }
    },
    computed:{
        getDate(){
            return this.dateFormat(this.user.lastLoginTime)
        },
        countData(){
            let accuracyRate=0.0
            let lossRate=0.0
            if(this.targetModel.model!=undefined){
                accuracyRate=this.targetModel.model.accuracyRate
                lossRate=this.targetModel.model.lossRate
                lossRate=Math.floor(lossRate * 1000) / 1000 
                accuracyRate=(Number(accuracyRate)*100).toFixed(2)
            }
            return [
                {
                name: "模型准确率",
                value: accuracyRate.toString()+"%",
                icon: "success",
                color: "#2ec7c9",
                },
                {
                name: "模型损失率",
                value: lossRate,
                icon: "s-help",
                color: "#ffb980",
                },
                {
                name: "模型版本",
                value: this.targetModel.model.modelName,
                icon: "star-on",
                color: "#5ab1ef",
                }
            ]
        }
       
    },
    mounted(){
        this.getUserInfo()
        this.getModelList()
        
    }
}
</script>


<style lang="less" scoped>

.user{
    padding-bottom: 20px;
    margin-bottom: 20px;
    border-bottom: 1px solid #ccc;
    display: flex;
    align-items: center;
    img{
        margin-right: 40px;
        width: 150px;
        height: 150px;
        border-radius: 50%;
    }
}
.userinfo{
    .name{
        font-size: 25px;
        margin-bottom: 10px;
    }
    .access{
        font-size: 10px;
        color: #999999;
    }
}
.login-info{
    p{
        line-height: 28px;
        font-size: 14ox;
        color: #999999;
        span{
            color: #666;
            margin-left: 60px;
        }
    }
}
.num{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .icon{
        width: 50px;
        height: 50px;
        font-size: 25px;
        text-align: center;
        line-height: 50px;
        color: #FFF;
    }
    .detail{
        margin-left: 15px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        .item_val{
            font-size: 20px;
            margin-bottom: 3px;
            line-height: 30px;
            height: 30px;
        }
        .item_name{
            font-size: 11px;
            color: #999;
            text-align: center;
        }
    }
    .el-card{
        width: 32%;
        margin-bottom: 20px;
    }
}
.graph{
    display: flex;
    justify-content: space-between;
    .el-card{
        margin-top: 20px;
        width: 48%;
    }
}
</style>